import { Graph, NodeData } from "@antv/g6";
import { useCallback, useEffect, useRef } from "react";

interface INodeData extends NodeData {
  data?: { label: string; width: number; height: number };
}

const ChartDemo1 = () => {
  const ref = useRef<HTMLDivElement & { graph?: Graph }>(null);

  const getData = useCallback(() => {
    const data = {
      nodes: [
        {
          id: "kspacey",
          data: { label: "Kevin Spacey", width: 144, height: 100 },
        },
        {
          id: "swilliams",
          data: { label: "Saul Williams", width: 160, height: 100 },
        },
        { id: "bpitt", data: { label: "Brad Pitt", width: 108, height: 100 } },
        {
          id: "hford",
          data: { label: "Harrison Ford", width: 168, height: 100 },
        },
        {
          id: "lwilson",
          data: { label: "Luke Wilson", width: 144, height: 100 },
        },
        {
          id: "kbacon",
          data: { label: "Kevin Bacon", width: 121, height: 100 },
        },
      ],
      edges: [
        { id: "kspacey->swilliams", source: "kspacey", target: "swilliams" },
        { id: "swilliams->kbacon", source: "swilliams", target: "kbacon" },
        { id: "bpitt->kbacon", source: "bpitt", target: "kbacon" },
        { id: "hford->lwilson", source: "hford", target: "lwilson" },
        { id: "lwilson->kbacon", source: "lwilson", target: "kbacon" },
      ],
    };

    ref.current.graph.setData(data);
  }, []);

  useEffect(() => {
    const graph = new Graph({
      container: ref.current,
      background: "#F2F7FA",
      autoFit: "center",
      node: {
        type: "rect",
        style: {
          size: (d: INodeData) => [d.data.width, d.data.height],
          radius: 10,
          iconText: (d: INodeData) => d.data.label,
          iconFontSize: 14,
        },
        palette: {
          type: "group",
          field: "label",
        },
      },
      edge: {
        type: "polyline",
        style: {
          endArrow: true,
          router: {
            type: "orth",
          },
        },
      },
      layout: {
        type: "dagre",
      },
      animation: false,
    });
    ref.current.graph = graph;
    graph.render();

    getData();
  }, []);

  return (
    <>
      <h2>官方：图布局 Dagre</h2>
      <div ref={ref} style={{ width: "100%", minHeight: 600 }}></div>
    </>
  );
};

export default ChartDemo1;
